<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>共享出行 - 当前行程</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        
        .header {
            background-color: #007bff;
            color: white;
            padding: 0 20px;
            height: 50px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header h1 {
            margin: 0;
            font-size: 1.2rem;
        }
        .nav-buttons {
            display: flex;
            gap: 10px;
        }
        .nav-button {
            background: transparent;
            border: 1px solid rgba(255, 255, 255, 0.5);
            border-radius: 4px;
            color: white;
            padding: 6px 12px;
            cursor: pointer;
            transition: background-color 0.2s;
            font-size: 14px;
        }
        .nav-button:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }
        .username {
            margin-right: 15px;
            font-size: 14px;
        }
        
        .container {
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
        }
        
        .trip-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .trip-header {
            background: #e3f2fd;
            padding: 20px;
            border-bottom: 1px solid #e1e1e1;
        }
        
        .trip-body {
            padding: 20px;
        }
        
        .vehicle-info {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .vehicle-image {
            width: 80px;
            height: 80px;
            border-radius: 8px;
            margin-right: 15px;
            background: #f0f0f0;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .trip-details {
            margin-top: 20px;
            background: #f9f9f9;
            padding: 15px;
            border-radius: 8px;
        }
        
        .detail-item {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px dashed #eee;
        }
        
        .detail-item:last-child {
            border-bottom: none;
        }
        
        .trip-map {
            height: 250px;
            margin: 20px 0;
            border-radius: 8px;
            overflow: hidden;
        }
        
        .trip-actions {
            margin-top: 30px;
            text-align: center;
        }
        
        .button {
            padding: 12px 25px;
            font-size: 16px;
            font-weight: bold;
            border: none;
            border-radius: 8px;
            background: #f44336;
            color: white;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .button:hover {
            background: #d32f2f;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        
        .button.blue {
            background: #007bff;
        }
        
        .button.blue:hover {
            background: #0056b3;
        }
        
        .cost-counter {
            background: #fff3e0;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
            margin-top: 20px;
            position: relative;
        }
        
        .current-cost {
            font-size: 32px;
            font-weight: bold;
            color: #f57c00;
        }
        
        .duration {
            font-size: 14px;
            color: #666;
            margin-top: 5px;
        }
        
        .no-trip {
            text-align: center;
            padding: 40px 0;
        }
        
        .no-trip h2 {
            color: #666;
            margin-bottom: 20px;
        }
        
        .loading {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255,255,255,0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            display: none;
        }
        
        .spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid #007bff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .toast {
            position: fixed;
            bottom: 30px;
            right: 30px;
            background: #4caf50;
            color: white;
            padding: 15px 25px;
            border-radius: 4px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            z-index: 1010;
            opacity: 0;
            transform: translateY(20px);
            transition: opacity 0.3s, transform 0.3s;
        }
        
        .toast.show {
            opacity: 1;
            transform: translateY(0);
        }
        
        .toast.error {
            background: #f44336;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>共享出行系统</h1>
        <div class="nav-buttons">
            <span class="username" id="usernameDisplay"></span>
            <button class="nav-button" onclick="window.location.href='vehicle-list.html'">车辆租赁</button>
            <button class="nav-button" onclick="window.location.href='edit-profile.html'">个人资料</button>
            <button class="nav-button" onclick="logout()">退出登录</button>
        </div>
    </div>

    <div class="container" id="tripContainer">
        <!-- 行程内容将通过JavaScript动态生成 -->
        <div class="loading">
            <div class="spinner"></div>
        </div>
    </div>

    <div id="toast" class="toast"></div>

    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
    <script>
        let currentTrip = null;
        let tripMap = null;
        let costInterval = null;

        document.addEventListener('DOMContentLoaded', async function() {
            await checkLogin();
            fetchCurrentTrip();
        });

        // 检查登录状态
        async function checkLogin() {
            showLoading();
            try {
                const response = await fetch('api/check-login', { credentials: 'include' });
                const result = await response.json();
                
                if (!result.success) {
                    window.location.href = 'login.html';
                    return false;
                }
                
                // 显示用户名
                document.getElementById('usernameDisplay').textContent = result.data.username;
                
                hideLoading();
                return true;
            } catch (error) {
                console.error('检查登录状态失败:', error);
                window.location.href = 'login.html';
                hideLoading();
                return false;
            }
        }

        // 退出登录
        async function logout() {
            try {
                showLoading();
                const response = await fetch('api/logout', {
                    method: 'POST',
                    credentials: 'include'
                });
                const result = await response.json();
                
                hideLoading();
                if (result.success) {
                    window.location.href = 'login.html';
                }
            } catch (error) {
                hideLoading();
                console.error('退出登录失败:', error);
            }
        }

        // 获取当前行程
        async function fetchCurrentTrip() {
            showLoading();
            try {
                const response = await fetch('api/rental/current', { 
                    credentials: 'include' 
                });
                const result = await response.json();
                
                hideLoading();
                console.log('Current trip response:', result);
                
                if (result.success && result.active) {
                    currentTrip = result.data;
                    displayTrip(currentTrip);
                    startCostCounter();
                } else {
                    displayNoTrip();
                }
            } catch (error) {
                hideLoading();
                console.error('获取行程失败:', error);
                showToast('获取行程信息失败', true);
                displayNoTrip();
            }
        }

        // 显示行程信息
        function displayTrip(trip) {
            const vehicle = trip.vehicle;
            const startTime = new Date(trip.startTime).toLocaleString();
            
            const tripHtml = `
                <div class="trip-card">
                    <div class="trip-header">
                        <h2>进行中的行程</h2>
                    </div>
                    <div class="trip-body">
                        <div class="vehicle-info">
                            <div class="vehicle-image">
                                <span style="font-size: 40px;">🚲</span>
                            </div>
                            <div>
                                <h3>${getTypeText(vehicle.type)} ${vehicle.brand} ${vehicle.model}</h3>
                                <p>车牌号: ${vehicle.plateNumber}</p>
                            </div>
                        </div>
                        
                        <div class="cost-counter">
                            <div class="current-cost" id="currentCost">¥${trip.estimatedAmount || '0.00'}</div>
                            <div class="duration" id="tripDuration">已行驶 ${formatDuration(trip.durationMinutes || 0)}</div>
                        </div>
                        
                        <div class="trip-details">
                            <div class="detail-item">
                                <span>开始时间</span>
                                <span>${startTime}</span>
                            </div>
                            <div class="detail-item">
                                <span>单价</span>
                                <span>¥${vehicle.pricePerMinute}/分钟</span>
                            </div>
                            <div class="detail-item">
                                <span>租赁ID</span>
                                <span>${trip.id}</span>
                            </div>
                        </div>
                        
                        <div id="tripMap" class="trip-map"></div>
                        
                        <div class="trip-actions">
                            <button class="button" onclick="endTrip()">结束行程</button>
                        </div>
                    </div>
                </div>
            `;
            
            document.getElementById('tripContainer').innerHTML = tripHtml;
            
            // 初始化地图
            setTimeout(() => {
                initTripMap(trip);
            }, 100);
        }

        // 显示无行程页面
        function displayNoTrip() {
            const noTripHtml = `
                <div class="no-trip">
                    <h2>您当前没有进行中的行程</h2>
                    <p>前往车辆列表页面租赁车辆</p>
                    <button class="button blue" style="margin-top: 20px;" onclick="window.location.href='vehicle-list.html'">去租车</button>
                </div>
            `;
            
            document.getElementById('tripContainer').innerHTML = noTripHtml;
        }

        // 初始化地图
        function initTripMap(trip) {
            const mapElement = document.getElementById('tripMap');
            if (!mapElement) return;
            
            const startLat = trip.vehicle.latitude || 30.274084;
            const startLng = trip.vehicle.longitude || 120.155070;
            
            tripMap = L.map('tripMap').setView([startLat, startLng], 15);
            
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; OpenStreetMap contributors'
            }).addTo(tripMap);
            
            // 添加车辆标记
            L.marker([startLat, startLng]).addTo(tripMap)
                .bindPopup(`${trip.vehicle.brand} ${trip.vehicle.model}`)
                .openPopup();
        }

        // 启动费用计算器
        function startCostCounter() {
            if (costInterval) {
                clearInterval(costInterval);
            }
            
            if (!currentTrip || !currentTrip.vehicle) return;
            
            // 计算起始分钟数
            const startTime = new Date(currentTrip.startTime).getTime();
            const pricePerMinute = currentTrip.vehicle.pricePerMinute;
            
            costInterval = setInterval(() => {
                const now = new Date().getTime();
                const diffMinutes = Math.floor((now - startTime) / (1000 * 60));
                const cost = (diffMinutes * pricePerMinute).toFixed(2);
                
                document.getElementById('currentCost').textContent = `¥${cost}`;
                document.getElementById('tripDuration').textContent = `已行驶 ${formatDuration(diffMinutes)}`;
            }, 10000); // 每10秒更新一次
            
            // 立即执行一次更新
            const now = new Date().getTime();
            const diffMinutes = Math.floor((now - startTime) / (1000 * 60));
            const cost = (diffMinutes * pricePerMinute).toFixed(2);
            
            document.getElementById('currentCost').textContent = `¥${cost}`;
            document.getElementById('tripDuration').textContent = `已行驶 ${formatDuration(diffMinutes)}`;
        }

        // 结束行程
        async function endTrip() {
            if (!currentTrip) return;
            
            if (!confirm('确定要结束当前行程吗？')) {
                return;
            }
            
            showLoading();
            
            try {
                // 获取当前位置
                const position = await getCurrentPosition();
                
                const response = await fetch('api/rental/end', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        vehicleId: currentTrip.vehicleId,
                        longitude: position ? position.longitude : null,
                        latitude: position ? position.latitude : null
                    }),
                    credentials: 'include'
                });
                
                const result = await response.json();
                console.log('End trip response:', result);
                
                hideLoading();
                
                if (result.success) {
                    showToast('行程已结束');
                    
                    // 清除计费计时器
                    if (costInterval) {
                        clearInterval(costInterval);
                        costInterval = null;
                    }
                    
                    // 显示行程结束信息
                    setTimeout(() => {
                        alert(`行程已结束\n总费用: ¥${result.data.totalAmount || '0.00'}\n感谢您使用共享出行系统！`);
                        window.location.href = 'vehicle-list.html';
                    }, 1000);
                } else {
                    showToast(result.message || '结束行程失败', true);
                }
            } catch (error) {
                hideLoading();
                console.error('结束行程失败:', error);
                showToast('结束行程失败，请稍后重试', true);
            }
        }

        // 获取当前位置
        function getCurrentPosition() {
            return new Promise((resolve, reject) => {
                if (!navigator.geolocation) {
                    resolve(null);
                    return;
                }
                
                navigator.geolocation.getCurrentPosition(
                    (position) => {
                        resolve({
                            latitude: position.coords.latitude,
                            longitude: position.coords.longitude
                        });
                    },
                    (error) => {
                        console.warn('获取位置失败:', error);
                        resolve(null);
                    },
                    { timeout: 5000 }
                );
            });
        }

        // 格式化时长显示
        function formatDuration(minutes) {
            if (minutes < 60) {
                return `${minutes} 分钟`;
            } else {
                const hours = Math.floor(minutes / 60);
                const mins = minutes % 60;
                return `${hours} 小时 ${mins} 分钟`;
            }
        }

        // 获取车辆类型文本
        function getTypeText(type) {
            switch (type) {
                case 'car': return '汽车';
                case 'e-bike': return '电动车';
                case 'bicycle': return '自行车';
                default: return type;
            }
        }

        // 显示加载动画
        function showLoading() {
            const loading = document.querySelector('.loading');
            if (loading) loading.style.display = 'flex';
        }

        // 隐藏加载动画
        function hideLoading() {
            const loading = document.querySelector('.loading');
            if (loading) loading.style.display = 'none';
        }

        // 显示提示信息
        function showToast(message, isError = false) {
            const toast = document.getElementById('toast');
            if (!toast) return;
            
            toast.textContent = message;
            toast.className = 'toast';
            if (isError) toast.classList.add('error');
            toast.classList.add('show');
            
            setTimeout(() => {
                toast.classList.remove('show');
            }, 3000);
        }
    </script>
</body>
</html> 